mod commands;
mod service;

use std::io::Read;
use std::sync::Arc;
use std::{io, thread};

use grpcio::{Environment, ServerBuilder};

use futures::channel::oneshot;
use futures::executor::block_on;

use crate::commands::redis_grpc;
use grpcio_health::HealthService;
use service::RedisService;

fn main() {
    let env = Arc::new(Environment::new(1));

    let health_service = grpcio_health::create_health(HealthService::default());
    let redis_service = redis_grpc::create_redis(RedisService::default());

    let mut server = ServerBuilder::new(env)
        .register_service(health_service)
        .register_service(redis_service)
        .bind("127.0.0.1", 8080)
        .build()
        .unwrap();
    server.start();

    for (ref host, port) in server.bind_addrs() {
        println!("listening on {}:{}", host, port);
    }

    let (tx, rx) = oneshot::channel();
    thread::spawn(move || {
        println!("Press ENTER to exit...");
        let _ = io::stdin().read(&mut [0]).unwrap();
        tx.send(())
    });
    let _ = block_on(rx);
    let _ = block_on(server.shutdown());
}
